import {config} from '../config.js'
const tips = {
    1: '抱歉，出现了一个错误',
    1005: 'token无效',
    101: '登录信息失效，请重新登录！'
}

// # 解构
class HTTP {
    request({url, data = {}, method = 'GET'}) {
        return new Promise((resolve, reject) => {
            this._request(url, resolve, reject, data, method)
        })
    }

    _request(url, resolve, reject, data = {}, method = 'GET') {
        const studentID = wx.getStorageSync('userInfo')?JSON.parse(wx.getStorageSync('userInfo')).id:''
        wx.request({
            url: config.api_base_url + url,
            method: method,
            data: data,
            header: {
                'content-type': 'application/json',
                'token': wx.getStorageSync('token') || '',
                'studentID': studentID
            },
            success: (res) => {
                const code = res.statusCode.toString()
                if (code.startsWith('2')) {
                    //判断token是否过期
                    const data_code = res.data.code
                    if (data_code == 101) {
                        reject()
                        this._show_error(data_code)
                        //清除session
                        wx.clearStorage()
                        //跳转到登录
                        wx.reLaunch({
                            url: '/pages/login/login'
                        })
                    } else {
                        resolve(res.data)
                    }
                } else {
                    reject()
                    const error_code = res.data.code
                    this._show_error(error_code)
                }
            },
            fail: (err) => {
                reject()
                this._show_error(1)
            }
        })

    }

    _show_error(error_code) {
        if (!error_code) {
            error_code = 1
        }
        const tip = tips[error_code]
        wx.showToast({
            title: tip ? tip : tips[1],
            icon: 'none',
            duration: 2000
        })
    }


}

export {HTTP}
